package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller统一异常处理类
 * @author XB on 2021/8/24 0024.
 * @version 3.0
 */
@Slf4j
/*@ResponseBody
@ControllerAdvice*/
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public R handleVaildException(MethodArgumentNotValidException e){
		log.error("错误异常，{}",e.getMessage());
		Map<String,String> map=new HashMap<>();
		e.getBindingResult().getFieldErrors().forEach((item)->{
			//获取异常类型
			String name = item.getField();

			//获取异常信息
			String errorMessage = item.getDefaultMessage();
			map.put(name,errorMessage);
		});
		return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
	}

	/***
	 * 统一异常处理
	 * @param throwable
	 * @return
	 */
	@ExceptionHandler(value = Throwable.class)
	public R handleException(Throwable throwable){

		return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
	}

}
